from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import datetime
import sys
import os

class InfoForm(QWidget):

    finish_signal = pyqtSignal(str, str)
    pwd = os.getcwd() + "/Data"

    def __init__(self):
        super(InfoForm, self).__init__()

        self.lbl_test = QLabel('测试项目', self)
        self.setWindowTitle("新建测试")
        self.btn_save = QPushButton('保存路径', self)
        self.btn_save.clicked.connect(self.open_file_dialog)
        self.btn_finish = QPushButton('完成', self)
        self.btn_finish.clicked.connect(self.finish_and_save)
        self.btn_cancel = QPushButton('取消', self)
        self.btn_cancel.clicked.connect(self.cancel_and_close)

        self.lineedit_test = QLineEdit(self)
        self.lineedit_test.setPlaceholderText('请输入测试项目名')
        date = datetime.datetime.now()
        dirname = "/转矩流变仪(%s%s%s%s%s%s)" % (date.year, date.month, date.day, date.hour, date.minute, date.second)
        self.lineedit_test.setText(dirname)
        self.textedit_path = QTextEdit(self)
        self.textedit_path.setPlaceholderText('点击左边按钮选择保存路径')
        self.textedit_path.setText(self.pwd)
        self.textedit_path.setReadOnly(True)

        self.grid_layout = QGridLayout()
        self.grid_layout.addWidget(self.lbl_test, 1, 1)
        self.grid_layout.addWidget(self.lineedit_test, 1, 2)
        self.grid_layout.addWidget(self.btn_save, 2, 1)
        self.grid_layout.addWidget(self.textedit_path, 2, 2)

        self.grid_layout.addWidget(self.btn_cancel, 3, 1)
        self.grid_layout.addWidget(self.btn_finish, 3, 2)

        self.setLayout(self.grid_layout)

    def updateFilename(self):
        """每次打开这个窗口都会调用这个函数，由主窗口的“新建测试”按钮触发带哦用改函数"""
        date = datetime.datetime.now()
        dirname = "/转矩流变仪(%s%s%s%s%s%s)" % (date.year, date.month, date.day, date.hour, date.minute, date.second)
        self.lineedit_test.setText(dirname)

    def open_file_dialog(self):
        dir_choose = QFileDialog.getExistingDirectory(self, '选择文件夹', self.pwd)
        self.textedit_path.setText(dir_choose)

    def finish_and_save(self):
        if not self.lineedit_test.text():
            QMessageBox.critical(self, '注意', '测试项目名不能为空！')
            self.lineedit_test.setFocus()
        elif not self.textedit_path.toPlainText():
            QMessageBox.critical(self, '注意', '保存路径不能为空！')
        else:
            self.finish_signal.emit(self.textedit_path.toPlainText(), self.lineedit_test.text())
            self.close()

    def cancel_and_close(self):
        self.close()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    form = InfoForm()
    form.show()
    sys.exit(app.exec_())